package com.gzc.just.play.last.war.centralserver.handler;

import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.centralserver.service.RankingService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 排行榜处理器
 * 处理排行榜相关的消息，如获取排行榜列表、获取个人排名等
 */
@Component("central-rankingHandler")
public class RankingHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(RankingHandler.class);
    
    @Autowired
    private RankingService rankingService;
    
    private static final int RANKING = 3004;
    
    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        // 从上下文中获取玩家ID
        io.netty.util.AttributeKey<Long> playerIdKey = io.netty.util.AttributeKey.valueOf("playerId");
        Long playerId = ctx.channel().attr(playerIdKey).get();
        
        // 从消息中解析操作类型
        String operation = extractOperation(message);
        
        switch (operation) {
            case "getRankingList":
                handleGetRankingList(message, ctx);
                break;
            case "getPlayerRanking":
                handleGetPlayerRanking(playerId, message, ctx);
                break;
            case "getFriendRanking":
                handleGetFriendRanking(playerId, message, ctx);
                break;
            default:
                logger.warn("Unknown ranking operation: {}", operation);
                break;
        }
    }
    
    /**
     * 处理获取排行榜列表请求
     */
    private void handleGetRankingList(Object message, ChannelHandlerContext ctx) {
        // 从消息中解析排行榜类型和范围
        String rankingType = extractRankingType(message);
        int limit = extractLimit(message, 50); // 默认返回前50名
        int offset = extractOffset(message, 0); // 默认从第0名开始
        
        // 获取排行榜列表
        List<Map<String, Object>> rankingList = rankingService.getRankingList(rankingType, limit);
        
        // 发送排行榜列表响应
        sendRankingListResponse(ctx, rankingList, rankingType, limit, offset, 
                              true, "Ranking list retrieved successfully");
        
        logger.info("Retrieved {} ranking list for type: {}", rankingList.size(), rankingType);
    }
    
    /**
     * 处理获取玩家排名请求
     */
    private void handleGetPlayerRanking(Long playerId, Object message, ChannelHandlerContext ctx) {
        // 从消息中解析排行榜类型
        String rankingType = extractRankingType(message);
        
        // 获取目标玩家ID（如果有）
        Long targetPlayerId = extractTargetPlayerId(message);
        if (targetPlayerId == null) {
            targetPlayerId = playerId; // 默认获取自己的排名
        }
        
        // 获取玩家排名
        Map<String, Object> playerRanking = rankingService.getPlayerRanking(targetPlayerId, rankingType);
        
        // 发送玩家排名响应
        if (playerRanking != null) {
            sendPlayerRankingResponse(ctx, playerRanking, rankingType, targetPlayerId, 
                                    true, "Player ranking retrieved successfully");
            logger.info("Retrieved ranking for player: {}", targetPlayerId);
        } else {
            sendPlayerRankingResponse(ctx, null, rankingType, targetPlayerId, 
                                    false, "Player not found in ranking: " + targetPlayerId);
            logger.warn("Player not found in ranking: {}", targetPlayerId);
        }
    }
    
    /**
     * 处理获取好友排名请求
     */
    private void handleGetFriendRanking(Long playerId, Object message, ChannelHandlerContext ctx) {
        // 从消息中解析排行榜类型
        String rankingType = extractRankingType(message);
        
        // 获取好友排名
        List<Map<String, Object>> friendRanking = rankingService.getFriendRanking(playerId, rankingType);
        
        // 发送好友排名响应
        sendFriendRankingResponse(ctx, friendRanking, rankingType, playerId, 
                                true, "Friend ranking retrieved successfully");
        
        logger.info("Retrieved {} friend rankings for player: {}", friendRanking.size(), playerId);
    }
    
    // 以下是辅助方法，用于从消息中提取数据
    
    private String extractOperation(Object message) {
        // 实际实现中应从消息对象中解析操作类型
        return "getRankingList"; // 简化实现
    }
    
    private String extractRankingType(Object message) {
        // 实际实现中应从消息对象中解析排行榜类型
        return "score"; // 默认类型
    }
    
    private int extractLimit(Object message, int defaultValue) {
        // 实际实现中应从消息对象中解析限制数量
        return defaultValue;
    }
    
    private int extractOffset(Object message, int defaultValue) {
        // 实际实现中应从消息对象中解析偏移量
        return defaultValue;
    }
    
    private Long extractTargetPlayerId(Object message) {
        // 实际实现中应从消息对象中解析目标玩家ID
        return null;
    }
    
    // 以下是发送响应的方法
    
    private void sendRankingListResponse(ChannelHandlerContext ctx, List<Map<String, Object>> rankingList,
                                       String rankingType, int limit, int offset, boolean success, String message) {
        // 实际实现中应构造响应消息并发送给客户端
        logger.debug("Sending ranking list response: success={}, count={}", success, rankingList.size());
    }
    
    private void sendPlayerRankingResponse(ChannelHandlerContext ctx, Map<String, Object> playerRanking,
                                         String rankingType, Long playerId, boolean success, String message) {
        // 实际实现中应构造响应消息并发送给客户端
        logger.debug("Sending player ranking response: success={}, playerId={}", success, playerId);
    }
    
    private void sendFriendRankingResponse(ChannelHandlerContext ctx, List<Map<String, Object>> friendRanking,
                                         String rankingType, Long playerId, boolean success, String message) {
        // 实际实现中应构造响应消息并发送给客户端
        logger.debug("Sending friend ranking response: success={}, count={}, playerId={}", 
                    success, friendRanking.size(), playerId);
    }
    
    @Override
    public Logger getLogger() {
        return logger;
    }
    
    @Override
    public int getMessageId() {
        return RANKING;
    }
    
    @Override
    public String getName() {
        return "RankingHandler";
    }
}